using UnityEngine;
using System.Collections;

public class GameHandler : MonoBehaviour {
	
	public GameObject nextLevelButton;
	public InputHandler inputHandler;
	
	public string[] levels;
	public int currentLevelIndex = 0;
	
	private float activationTime = 0;
	private bool finished = false;
	
	public int endWaitTime = 10;
	
	void Start () {
		LevelHandler.Instance.loadLevel(levels[currentLevelIndex]);
		
		StatsHandler.Instance.newLevel(levels[currentLevelIndex]);
		
		NGUITools.SetActive(nextLevelButton,false);
		
	}
	
	void Update(){
		if(currentLevelIndex == levels.Length-1){
			return;
		}
		
		if(!finished){
			if(LevelConstants.nbActivatedReceivers == LevelConstants.nbReceivers && LevelConstants.nbReceivers != 0 && !LevelConstants.editorMode && !THistory.Instance.isUndoing()){
				if(activationTime == 0){
					activationTime = Time.time;	
				}
				
				if(Time.time - activationTime > 1){
					finished = true;
					
					StatsHandler.Instance.setTime();
					
					InfoDisplay.Instance.displayMessage("niveau termine !",3);
					NGUITools.SetActive(nextLevelButton,true);
					inputHandler.disable();
				}
				
			}else{
				activationTime = 0;	
			}
		}
	}
	
	private void initScene(){
		InfoDisplay.Instance.hideMessageNow();
		NGUITools.SetActive(nextLevelButton,false);
		activationTime = 0;
		THistory.Instance.clear();
		StatesHandler.Instance.clear();
		inputHandler.enable();
	}
	
	public void loadNextLevel(){
		initScene();
		
		currentLevelIndex++;
		
		if(currentLevelIndex == levels.Length){
			currentLevelIndex = 0;	
			StatsHandler.Instance.exportSessionStats();
			StatsHandler.Instance.reset();
		}
		
		LevelHandler.Instance.loadLevel(levels[currentLevelIndex]);
		StatsHandler.Instance.newLevel(levels[currentLevelIndex]);
		
		finished = false;
	}
	
	public void loadPreviousLevel(){
		initScene();
		
		currentLevelIndex--;
		
		if(currentLevelIndex < 0){
			currentLevelIndex = levels.Length-1;	
		}
		
		LevelHandler.Instance.loadLevel(levels[currentLevelIndex]);
		StatsHandler.Instance.newLevel(levels[currentLevelIndex]);
		
		finished = false;
	}

}
